from time import strftime
from time import localtime
from time import time
import pymysql
import schedule
import os
import queue
from threading import Thread
#数据库地址
SQL_HOST='xxx.xx.xx.xx'
SQL_PORT=3306
#数据库登录的帐号密码
SQL_user='xxxx'
SQL_pass='xxxxx'
#数据库名字必须是'Hey_guys'
SQL_DBname='Hey_guys'

#发送消息的队列
send_list=queue.Queue()

#发送消息进程是否运行
ising_send=False
#发送消息的函数
def run_send():
    global ising_send
    ising_send=True
    while not send_list.empty():
        i = send_list.get()
        cmd='qq send %s %s 嘿,朋友.别忘了: %s'%(i[5],i[6],i[3])
        print(cmd)
        os.system(cmd)
        
    ising_send=False
def runn():
    global ising_send
    nowtime=strftime('%Y%m%d%H%M',localtime(time()))
    print(nowtime,"运行了")
    db=pymysql.connect(host=SQL_HOST,port=SQL_PORT,user=SQL_user,password=SQL_pass,db=SQL_DBname,charset='utf8')
    cursor = db.cursor()
    try:
        sql='SELECT * FROM run WHERE user_time=%s'%(nowtime)
        if(cursor.execute(sql.encode('utf8'))==0):
            db.close()
            return
        else:
            result = cursor.fetchall()
            db.commit()
            for i in result:
                send_list.put(i)
                if(ising_send==False):
                    ti=Thread(target=run_send)
                    ising_send=True
                    ti.start()
                print(i)
                sql='INSERT INTO alread(ran_code,user_time,context,approach,obj_type,user_num,sub_time,send_time) VALUES(\'%d\',\'%s\',\'%s\',\'%s\',\'%s\',\'%s\',\'%s\',\'%s\')'%tuple((i[1:])+(nowtime,))
                cursor.execute(sql.encode('utf8'))
                db.commit()
                sql='DELETE FROM run WHERE id=%d'%(i[0])
                cursor.execute(sql.encode('utf8'))
                db.commit()
    except:
        print('有异常')
        db.rollback()
    db.close()
schedule.every(60).seconds.do(runn)
while True:
    schedule.run_pending()